package com.sskj.gateway.controller;

import com.sskj.common.enums.ApiResponseCodeEnum;
import com.sskj.common.util.ApiResponseUtil;
import com.sskj.common.vo.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        // 构造错误信息：可以是简单字符串，也可以是结构化数据
        String errorMessage = fieldErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return ApiResponseUtil.fail(ApiResponseCodeEnum.REQUEST_PARAMS_VALIDATE_FAILED, errorMessage);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ApiResponse<Object> httpMessageNotReadableException() {
        return ApiResponseUtil.fail(ApiResponseCodeEnum.REQUEST_PARAMS_VALIDATE_FAILED, "缺少必要的请求参数");
    }
}
